import {getMenu} from "../../api/menu";
import {generator} from "../../utils/generator";
import storage from 'store'

const menu = {
    state: {
        menulist : storage.get("menulist") ? JSON.parse(storage.get("menulist")) : [],
        activeIndex:storage.get('activeIndex'),
        sideMenu:storage.get('sideMenu')||[]
    },
    mutations:{
        SET_MENU(state:any,menu:any){
            state.menulist = menu
        },
        SET_ACTIVE(state:any,active:string){
            state.activeIndex = active
        },
        SET_SIDEMENU(state:any,active:string){
            state.menulist.forEach((item:any)=>{
                if(item.path === active){
                    state.sideMenu = item.children
                    storage.set('sideMenu',item.children)
                }
            })
        }
    },
    actions:{
        setMenu({commit}:any){
            return new Promise((resolve, reject) => {
                getMenu().then(res=>{
                    commit('SET_MENU',res.data)
                    storage.set("menulist",JSON.stringify(res.data))
                    if(!storage.get('activeIndex')){
                        commit('SET_SIDEMENU',res.data[0].path)
                        commit('SET_ACTIVE',res.data[0].path)
                    }
                    resolve(generator(res.data))
                }).catch((err)=>{
                    reject(err)
                })
            })
        },
        setSideMenu({commit}:any,active:string){
            commit('SET_ACTIVE',active)
            storage.set("activeIndex",active)
            commit('SET_SIDEMENU',active)
        }
    }
}

export default menu
